package org.feng.framework.support;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import org.feng.framework.xss.XssUtil;
import org.springframework.boot.configurationprocessor.json.JSONArray;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.boot.configurationprocessor.json.JSONTokener;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author feng
 */
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {

    public XssHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
    }

    @Override
    public String[] getParameterValues(String name) {
        String[] values = super.getParameterValues(name);
        if (values != null) {
            int length = values.length;
            String[] value = new String[length];
            for (int i = 0; i < length; i++) {
                // 防xss攻击和过滤前后空格
                value[i] = XssUtil.stripXss(values[i]).trim();
            }
            return value;
        }
        return super.getParameterValues(name);
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        // 非json类型，直接返回
        if (!isJsonRequest()) {
            return super.getInputStream();
        }

        // 为空，直接返回
        String json = IoUtil.read(super.getInputStream(), "utf-8");
        if (StrUtil.isEmpty(json)) {
            return super.getInputStream();
        }
        if (!XssUtil.checkIsXss(json)){
            return super.getInputStream();
        }
        // xss过滤
        try {
            Object typeObject = new JSONTokener(json).nextValue();
            if (typeObject instanceof JSONArray) {
                com.alibaba.fastjson.JSONArray array = JSON.parseArray(json);
                for (Object o : array) {
                    com.alibaba.fastjson.JSONObject object = JSON.parseObject(JSON.toJSONString(o));
                    for (String s : object.keySet()) {
                        if (object.get(s.trim()) != null) {
                            object.put(s, XssUtil.stripXss(object.get(s.trim()).toString()));
                        }
                    }
                }
                json = JSON.toJSONString(array);
            } else if (typeObject instanceof JSONObject) {
                com.alibaba.fastjson.JSONObject object = JSON.parseObject(json);
                for (String s : object.keySet()) {
                    if (object.get(s.trim()) != null) {

                        object.put(s, XssUtil.stripXss(object.get(s.trim()).toString()));
                    }
                }
                json = JSON.toJSONString(object);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        final ByteArrayInputStream bis = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8));
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return true;
            }

            @Override
            public boolean isReady() {
                return true;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
            }

            @Override
            public int read() {
                return bis.read();
            }
        };
    }

    /**
     * 是否是Json请求
     */
    private boolean isJsonRequest() {
        return MediaType.APPLICATION_JSON_VALUE.equalsIgnoreCase(super.getHeader(HttpHeaders.CONTENT_TYPE));
    }

}
